openerp.dzx_callcenter = function(instance) {
    var QWeb = instance.web.qweb,
    _t = instance.web._t;

    instance.web.dzx_callcenter = instance.web.dzx_callcenter || {};


    //呼叫中心顶部按钮
    instance.web.dzx_callcenter.CCTopButton = openerp.Widget.extend({
        template:'dzx_callcenter.CCTopButton',
        events: {
            "click": "clicked",
            "hover": "hovered"
        },
        init: function(parent, dashboard){
            this._super(parent);
            this.dashboard = dashboard;
        },

        //组件启动时进行呼叫中心初始化
        start: function(){
            var self = this;
            //检查当前用户是否有对应的呼叫中心坐席设置
            openerp.session.rpc("/callcenter/init",{}).then(function(extension) {
                //如果存在分机设置和分机号码存在
                if (extension.user_id && extension.cc_extno){
                    self.cc_user = extension.cc_user;
                    self.cc_extno = extension.cc_extno;
                    self.$el.find('#oe_topbar_ccbutton_icon').css("display", 'block');
                    openerp.bus.bus.start_polling();
                }
            });
        },
        clicked: function(ev) {
            ev.preventDefault();
            this.trigger("clicked");
        },
        hovered: function(ev){
            ev.preventDefault();
            this.trigger("hovered");
            //console.log(ev);
        },
        display_login: function(text){
            this.$el.find('#oe_topbar_ccbutton_icon').text(text);
            this.dashboard.$el.find('.oe_list_buttons').removeClass('cc_logout');
            this.dashboard.$el.find('.login-text').html('签入<span class="caret">').removeClass('btn-logout');
        },
        display_logout: function(text){
            this.dashboard.$el.find('.oe_list_buttons').addClass('cc_logout');
            this.dashboard.$el.find('.login-text').html('签出<span class="caret">').addClass('btn-logout');
            this.$el.find('#oe_topbar_ccbutton_icon').css("color", '#555').text(text);
        },
        display_online: function(text){
            this.$el.find('#oe_topbar_ccbutton_icon').css("color", 'white').text(text);
            this.dashboard.$el.find('.online-text').html('在线<span class="caret">').removeClass('btn-offline');
        },
        display_busy: function(text){
            this.$el.find('#oe_topbar_ccbutton_icon').css("color", 'gray').text(text);
            this.dashboard.$el.find('.online-text').html('离线<span class="caret">').addClass('btn-offline');
        },
        display_activity: function(text){
            this.$el.find('#oe_topbar_ccbutton_icon').css("color", 'white').text(text);
        },
        display_number: function(number){
            this.dashboard.$el.find('.call-number').text(number);
            this.dashboard.$el.find('.search-number').removeClass('hide')
            if (number.length == 11 && number.substring(0, 1) == '1'){
                this.dashboard.$el.find('.call-type').text('手机来电: ');
            }
            else{
                this.dashboard.$el.find('.call-type').text('座机来电: ');
                if (number.length == 8){
                    number = '021-' + number;
                    this.dashboard.$el.find('.call-number').text(number);
                }
            }
        },
    });

    //呼叫中心控制仪表盘
    instance.web.dzx_callcenter.CCDashboard = openerp.Widget.extend({
        template:'dzx_callcenter.CCDashboard',
        events: {
            "click": "clicked"
        },
        init: function(parent) {
            this._super(parent);
            this.shown = false;
            this.set("right_offset", 0);

            this.message_manager = new openerp.web.dzx_callcenter.MessageManager(this, this);
            this.action_manager = new instance.web.ActionManager(this);
            this.view = parent.view;
            self = this;
            this.rpc("/web/action/load", { action_id: "dzx_ext.apply_delivery_action" }).done(function(result) {
                //menu_id需要整数
                self.menu_id = $(document).find("a.oe_menu_leaf[data-action-id=" + result.id + "]").attr('data-menu') * 1;
            });
        },
        start: function() {
            var self = this;
            this.$el.css("right", -this.$el.outerWidth());
            this.calc_box();
            return;
        },

        clicked: function(ev) {
            ev.preventDefault();
            this.trigger("clicked");
            //如果点击签入
            if ($(ev.target).hasClass('switch-login')){
                this.switch_login()
            }
            //如果点击签出
            if ($(ev.target).hasClass('switch-logout')){
                this.switch_logout()
            }
            //如果点击在线（置闲）
            if ($(ev.target).hasClass('switch-online')){
                this.switch_online()
            }
            //如果点击离线（置忙）
            if ($(ev.target).hasClass('switch-busy')){
                this.switch_busy()
            }
            if ($(ev.target).hasClass('search-number')){
                if (!instance.webclient.has_uncommitted_changes()){
                    var call_number = this.$el.find('.call-number').text();
                    var context = {};
                    if (call_number.length == 11 && call_number.substring(0, 1) == '1'){
                        context['search_default_mobile_number'] = call_number;
                        context['default_mobile_number'] = call_number;
                    }
                    else{
                        context['search_default_phone_number'] = call_number;
                        context['default_phone_number'] = call_number;
                    }
                    var menu = instance.webclient.menu;
                    menu.menu_click(this.menu_id, {context: context});
                }
            }
        },

        //发送呼叫中心请求
        send: function(data){
            return openerp.session.rpc("/callcenter/post", {act_data: data});
        },

        //呼叫中心签入
        switch_login: function(){
            var cc_user = openerp.web.dzx_callcenter.top_button.cc_user;
            var cc_extno = openerp.web.dzx_callcenter.top_button.cc_extno;
            var data = {'act': 'login', 'User': cc_user, 'extno': cc_extno};
            return this.send(data);
        },
        //呼叫中心签出
        switch_logout: function(){
            var cc_user = openerp.web.dzx_callcenter.top_button.cc_user;
            var data = {'act': 'logout', 'User': cc_user};
            return this.send(data);
        },

        //在线（置闲）
        switch_online: function(){
            var cc_user = openerp.web.dzx_callcenter.top_button.cc_user;
            var cc_extno = openerp.web.dzx_callcenter.top_button.cc_extno;
            var data = {'act': 'online', 'User': cc_user, 'extno': cc_extno};
            return this.send(data);
        },
        //离线（置忙）
        switch_busy: function(){
            var cc_user = openerp.web.dzx_callcenter.top_button.cc_user;
            var data = {'act': 'busy', 'User': cc_user};
            return this.send(data);
        },

        calc_box: function() {
            var $topbar = window.$('#oe_main_menu_navbar'); // .oe_topbar is replaced with .navbar of bootstrap3
            var top = $topbar.offset().top + $topbar.height();
            top = Math.max(top - $(window).scrollTop(), 0);
            this.$el.css("top", top);
            this.$el.css("bottom", 0);
        },
        switch_display: function() {
            this.calc_box();
            var fct =  _.bind(function(place) {
                this.set("right_offset", place + this.$el.outerWidth());
            }, this);
            var opt = {
                step: fct,
            };
            if (this.shown) {
                this.$el.animate({
                    right: -this.$el.outerWidth(),
                }, opt);
                var document_width = $(document).width();
                window.$('.openerp_webclient_container').width(document_width);
            } else {
                this.$el.animate({
                    right: 0,
                }, opt);
                var document_width = $(document).width();
                window.$('.openerp_webclient_container').width(document_width - this.$el.outerWidth());
            }
            this.shown = ! this.shown;
        },
    });

    //消息管理
    instance.web.dzx_callcenter.MessageManager = openerp.Widget.extend({
        init: function(parent, dashboard, options) {
            var self = this;
            this._super(parent);
            this.dashboard = dashboard;
            this.options = _.clone(options) || {};
            // business
            this.sessions = {};
            this.bus = openerp.bus.bus;
            this.bus.on("notification", this, this.on_notification);

        },
        send_message: function(message, type) {
            var self = this;
            var send_it = function() {
                var data = {'act': 'login', 'User': '7802', UserId: '2', 'Pwd': 'a7def4cece2adde9a75e1588b9b8a4e9', 'extno': '1514'}
                return openerp.session.rpc("/callcenter/post", {act_data: data});
            };
            var tries = 0;
            send_it().fail(function(error, e) {
                e.preventDefault();
                tries += 1;
                if (tries < 3)
                    return send_it();
            });
        },

        //服务器线程结束后回调
        on_notification: function(notification) {
            var self = this;
            var channel = notification[0];
            var message = notification[1];
            console.log(notification);
            if((Array.isArray(channel) && (channel[1] === 'callcenter.extension'))){
                if (message && message['return']){
                    if (message['return']['code'] == '200') {
                        switch (message.act) {
                            //用户签入结果
                            case 'login':
                                openerp.web.dzx_callcenter.top_button.display_login('签入');
                                openerp.web.dzx_callcenter.top_button.dashboard.switch_online();
                                break;
                            //用户签出结果
                            case 'logout':
                                openerp.web.dzx_callcenter.top_button.display_logout('签出');
                                break;
                            //用户置闲结果
                            case 'online':
                                openerp.web.dzx_callcenter.top_button.display_online('空闲');
                                break;
                            //用户置忙结果
                            case 'busy':
                                openerp.web.dzx_callcenter.top_button.display_busy('离席');
                                break;
                        }
                    }
                    //Oper not logon(好像是呼叫中心客户端软件没有登录)
                    if (message['return']['code'] == '405') {
                        openerp.web.dzx_callcenter.top_button.display_logout('签出');
                    }

                    if (message['return']['status'] != undefined){
                        //SIP软件已登录(在线)
                        if (message['return']['epstatus'] == '3'){
                            openerp.web.dzx_callcenter.top_button.display_login('签入');
                            switch (message['return']['status']){
                                //未注册
                                case '0':
                                    openerp.web.dzx_callcenter.top_button.display_logout('未注册');
                                    break;
                                //空闲
                                case '1':
                                    openerp.web.dzx_callcenter.top_button.display_online('空闲');
                                    break;
                                //离席状态
                                case '2':
                                    openerp.web.dzx_callcenter.top_button.display_busy('离席');
                                    break;
                                //忙线
                                case '3':
                                    openerp.web.dzx_callcenter.top_button.display_activity('忙线');
                                    break;
                                //通话中
                                case '10':
                                    openerp.web.dzx_callcenter.top_button.display_activity('通话中');
                                    break;
                                //呼叫中
                                case '11':
                                    openerp.web.dzx_callcenter.top_button.display_activity('呼叫中');
                                    break;
                                //点拨中
                                case '12':
                                    openerp.web.dzx_callcenter.top_button.display_activity('响铃');
                                    var caller_number = message['return']['dn'];
                                    openerp.web.dzx_callcenter.top_button.display_number(caller_number);
                                    if (!openerp.web.dzx_callcenter.top_button.dashboard.shown){
                                        openerp.web.dzx_callcenter.top_button.dashboard.switch_display();
                                    }
                                    break;
                                //出错
                                default:
                                    openerp.web.dzx_callcenter.top_button.display_activity('出错');
                                    break;
                            }
                        }
                        //离线
                        else{
                            openerp.web.dzx_callcenter.top_button.display_logout('离线');
                        }
                    }
                }
            }
        }

    });

    if(openerp.web && openerp.web.UserMenu) {
        openerp.web.UserMenu.include({
            do_update: function(){
                var self = this;
                var Users = new openerp.web.Model('res.users');
                Users.call('has_group', ['base.group_user']).done(function(is_employee) {
                    if (is_employee) {
                        self.update_promise.then(function() {
                            var dashboard = new openerp.web.dzx_callcenter.CCDashboard(self);
                            dashboard.appendTo(openerp.client.$el);
                            var button = new openerp.web.dzx_callcenter.CCTopButton(self, dashboard);
                            //button.on("clicked", dashboard, dashboard.send_message);
                            openerp.web.dzx_callcenter.top_button = button;
                            button.on("clicked", dashboard, dashboard.switch_display);
                            button.appendTo(window.$('.oe_systray'));
                            //测试某号码拨入
                            //openerp.web.dzx_callcenter.top_button.display_number('13262569091');
                        });
                    }
                });
                return this._super.apply(this, arguments);
            },
        });
    }
}